package top.kaoshanji.p3ch14a;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 代码清单-p3ch14a-245页a：带有dispatch的简单的异步Servlet
 * URL访问地址：/asyncDispatch
 * @author kaoshanji
 * ^_^
 * create time 2025/4/9 15:36
 */
@WebServlet(name = "AsyncDispatchServlet", urlPatterns = {"/asyncDispatch"}, asyncSupported = true)
public class AsyncDispatchServlet extends HttpServlet {

    private static final long serialVersionUID = 222L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        final AsyncContext asyncContext = req.startAsync(); // 获得一个 AsyncContext

        // 定义两种线程，分别处理不同的逻辑
        // 主线程接收请求，工作线程处理请求，这，主线程的任务就大大减少了啊..就一个接收转移就完了
        req.setAttribute("mainThread", Thread.currentThread().getName()); // 主线程

        asyncContext.setTimeout(5000);
        asyncContext.start(new Runnable() {
            @Override
            public void run() {

                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    /// /
                }

                req.setAttribute("workerThread", Thread.currentThread().getName()); // 工作线程
                asyncContext.dispatch("/threadNames.jsp"); // 任务结束..就调用一下，让容器不用继续等待
            }
        });


    }

}
